using System.Linq;
using UnityEngine;

public class FemaleGhostController : MonoBehaviour
{
    [SerializeField] GameObject player;
    private PlayerController playerController;
    private Animator animator;
    private Light lightEat;
    [Header("吃玩家时的位置")]
    [SerializeField] Transform transformEat;
    
    private bool attacking = false;
    private bool isFaceToFace = false;

    void Awake()
    {
        playerController = player.GetComponent<PlayerController>();
        animator = GetComponent<Animator>();
        lightEat = gameObject.GetComponentsInChildren<Light>().Where(x => x.CompareTag(Defines.EatLight)).FirstOrDefault();
        this.lightEat.enabled = false;
    }

    void Start()
    {
        
    }

    void Update()
    {
        if (attacking)
        {
            Vector3 vector3 = new Vector3(player.transform.position.x, transform.position.y, player.transform.position.z);
            transform.LookAt(vector3);

            if (this.isFaceToFace)
            {
                // 面对
                if (Vector3.Angle(player.transform.forward, transform.forward) < 90)
                {
                    // 转到了背对
                    this.isFaceToFace = false;
                }
            }
            else
            {
                // 背对
                if (Vector3.Angle(player.transform.forward, transform.forward) > 90)
                {
                    // 转到了面对
                    this.isFaceToFace = true;
                    transform.position += (vector3 - transform.position) / 2;

                    if(Vector3.Distance(player.transform.position, transform.position) < 1)
                    {
                        playerController.Status = PlayerStatus.GetCaught;
                        EatPlayer();
                        // 玩家死亡，重启游戏
                        GameManager.Instance.DelayRestart(5);
                    }
                }
            }
        }
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag(Defines.Player))
        {
            this.attacking = true;
            this.isFaceToFace = true;
        }
    }

    private void EatPlayer()
    {
        this.animator.CrossFade(Defines.Eat, 1);
        this.lightEat.enabled = true;
        transform.position = this.transformEat.position;
    }
}
